package com.mywind.hbase.main;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Toolkit;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.SortedMap;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;

import com.mywind.hbase.common.InfiniteProgressPanel;
import com.mywind.hbase.common.SimpleFileFilter;

public class WFImporter{
	
	private static JFrame farm = new JFrame(" (●'◡'●)ﾉ 主数据导入神器");
	private static JPanel main = new JPanel();
	private static JLabel lab1 = new JLabel("<html><font color='red'>数据类型：</font></html>");
	private static JLabel lab2 = new JLabel("<html><font color='#8B4513'>文件编码：</font></html>");
	private static JLabel lab3 = new JLabel("<html><font color='green'>目标文件：</font></html>");
	private static JLabel lab4 = new JLabel("<html><font color='#567'>导入预览：</font></html>");
	private static JLabel lab5 = new JLabel("<html><font size='5' color='blue'>╰(*´︶`*)╯</font></html>",JLabel.CENTER);
	private static JComboBox<String> list = new JComboBox<String>();
	private static JTextArea  path = new JTextArea(3, 10);
	private static JTextArea  preview = new JTextArea(7, 10);
	private static JScrollPane jsp = new JScrollPane(preview);
	private static JScrollPane jsp2 = new JScrollPane(path);
	private static JFileChooser fc = new JFileChooser();
	private static ButtonGroup group = new ButtonGroup();
	private static JRadioButton r1 = new JRadioButton("<html><font color='#567'>风场主数据</font></html>");
	private static JRadioButton r2 = new JRadioButton("<html><font color='#567'>故障点主数据</font></html>");
	private static JButton btn = new JButton("导入");
	private static JButton btn2 = new JButton("选择文件");
	private static GridBagLayout gbl = new GridBagLayout();
	private static GridBagConstraints gbc = new GridBagConstraints();
	private static RunThread runThread;
	private static InfiniteProgressPanel glassPane = new InfiniteProgressPanel("导入进行时...");
	private static int WINDFARM = 1;
	private static String encode = "GBK";
	
	public static void main(String[] args) throws Exception{
		
		group.add(r1);
		group.add(r2);
		r1.setSelected(true);
		r1.addItemListener(new ItemListener() {
			
			public void itemStateChanged(ItemEvent e) {
				if(e.getSource() == r1)
					WINDFARM = 1;
			}
		});
		r2.addItemListener(new ItemListener() {
			
			public void itemStateChanged(ItemEvent e) {
				if(e.getSource() == r2)
					WINDFARM = 0;
			}
		});
		fc.setFileFilter(new SimpleFileFilter());
		main.setLayout(gbl);
		
		btn.addMouseListener(new MouseListener() {
			
			public void mouseReleased(MouseEvent e) {
				
			}
			
			public void mousePressed(MouseEvent e) {
				
			}
			
			public void mouseExited(MouseEvent e) {
				
			}
			
			public void mouseEntered(MouseEvent e) {
				
			}
			
			public void mouseClicked(MouseEvent e) {
				if(runThread != null && runThread.isAlive())
					runThread.interrupt();
				WFImporter wfi = new WFImporter();
				runThread = wfi.new RunThread();
				runThread.start();
			}
		});
		
		btn2.addMouseListener(new MouseListener() {
			
			public void mouseReleased(MouseEvent e) {
				
			}
			
			public void mousePressed(MouseEvent e) {
				
			}
			
			public void mouseExited(MouseEvent e) {
				
			}
			
			public void mouseEntered(MouseEvent e) {
				
			}
			
			public void mouseClicked(MouseEvent e) {
				int returnValue = fc.showOpenDialog(farm);
				if(returnValue == JFileChooser.APPROVE_OPTION){
					String realPath = fc.getSelectedFile().getPath();
					path.setText(realPath);
					setPreviewText();
				}
			}
		});
		
		list.addItemListener(new ItemListener() {
			
			public void itemStateChanged(ItemEvent e) {
				encode = e.getItem().toString();
				setPreviewText();
			}
		});
		
		gbc.fill = GridBagConstraints.BOTH;
		path.setEditable(false);
		path.setLineWrap(true);
		
		preview.setEditable(false);
		preview.setLineWrap(true);
		preview.setAutoscrolls(true);
		
		//row 1
		gbc.gridx = 0;
		gbc.gridy = 0;
		gbl.setConstraints(lab1, gbc);
		main.add(lab1);
		gbc.gridx = 1;
		gbc.gridy = 0;
		gbl.setConstraints(r1, gbc);
		main.add(r1);
		gbc.gridx = 2;
		gbc.gridy = 0;
		gbl.setConstraints(r2, gbc);
		main.add(r2);
		
		//row 2
		gbc.gridx = 0;
		gbc.gridy = 1;
		gbc.gridwidth = 1;
		gbl.setConstraints(lab2, gbc);
		main.add(lab2);
		gbc.gridx = 1;
		gbc.gridy = 1;
		gbc.gridwidth = 2;
		SortedMap<String, Charset> map = Charset.availableCharsets();
		Set<String> set = map.keySet();  
        Iterator<String> it = set.iterator();  
        while (it.hasNext()) {  
            String key = it.next();  
            Charset value = map.get(key);
            list.addItem(value.name());
        }  
        list.setSelectedItem("UTF-8");
		gbl.setConstraints(list, gbc);
		main.add(list);
		
		//row 3
		gbc.gridx = 0;
		gbc.gridy = 2;
		gbc.gridwidth = 3;
		gbl.setConstraints(lab3, gbc);
		main.add(lab3);
		
		//row 4
		gbc.gridx = 0;
		gbc.gridy = 3;
		gbc.gridwidth = 3;
		jsp2.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
		jsp2.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		gbl.setConstraints(jsp2, gbc);
		main.add(jsp2);
		
		//row 5
		gbc.gridx = 0;
		gbc.gridy = 4;
		gbc.gridwidth = 3;
		gbl.setConstraints(lab4, gbc);
		main.add(lab4);
		
		//row 6
		gbc.gridx = 0;
		gbc.gridy = 5;
		gbc.gridwidth = 3;
		jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
		jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		gbl.setConstraints(jsp, gbc);
		main.add(jsp);
		
		//row 7
		gbc.gridx = 0;
		gbc.gridy = 6;
		gbc.gridwidth = 1;
		gbl.setConstraints(btn2, gbc);
		main.add(btn2);
		gbc.gridx = 1;
		gbl.setConstraints(lab5, gbc);
		main.add(lab5);
		gbc.gridx = 2;
		gbc.gridy = 6;
		gbl.setConstraints(btn, gbc);
		main.add(btn);
		
		farm.add(main);
		farm.setLocation((int)Toolkit.getDefaultToolkit().getScreenSize().getWidth()/2 - 200, (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight()/2 - 100);
		farm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		farm.setSize(300, 310);
		farm.setResizable(false);
		farm.setGlassPane(glassPane);
		farm.setVisible(true);
	}
	
	private static void setPreviewText(){
		if(path.getText()!=null && !"".equals(path.getText().trim())){
			File file = new File(path.getText());
			if(file.exists()){
				try {
				    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), list.getSelectedItem().toString()));
				    String sLine = null;
				    StringBuffer buf = new StringBuffer();
				    while((sLine = br.readLine()) != null){
				    	buf.append(sLine);
				    	buf.append("\r\n");
				    }
				    preview.setText(buf.toString());
					br.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
	}
	
	private class RunThread extends Thread{
		@Override
		public void run() {
			String tableName = "";
			String[] family = null, qualifier = null;
        	switch(WINDFARM){
        	case 0:
        		tableName = "breakpoint";
        		family = new String[]{"prop"};
        		qualifier = new String[]{"code","name"};
        		break;
        	case 1:
        		tableName = "windfarm";
        		family = new String[]{"prop"};
        		qualifier = new String[]{"code","name"};
        		break;
        	default:
        		JOptionPane.showMessageDialog(farm, "请选择一个数据类型 ｡:.ﾟヽ(｡◕‿◕｡)ﾉﾟ.:｡+ﾟ ");
        		return;
        	}
        	if(path.getText() == null || "".equals(path.getText())){
        		JOptionPane.showMessageDialog(farm, "请选择一个txt文件 ԅ(¯﹃¯ԅ)");
        		return;
        	}
			InfiniteProgressPanel gl = glassPane;
			gl.start();
            gl.setText("正在导入系统...");
//            192.168.8.184   master
//            192.168.8.183   slave1
//            192.168.8.178   slave2
//            192.168.8.190   slave3
//            192.168.8.167   slave4
//            192.168.8.169   slave5
//            192.168.8.170   slave6
//            192.168.8.172   slave7
//            192.168.8.182   slave8
//            192.168.8.175   slave9
//            192.168.8.179   slave10
            Configuration conf = HBaseConfiguration.create();
            conf.set("hbase.zookeeper.quorum", "192.168.8.184,192.168.8.183,192.168.8.178,192.168.8.190,192.168.8.167,192.168.8.169,192.168.8.170,192.168.8.172,192.168.8.182,192.168.8.175,192.168.8.179");   
            conf.set("hbase.zookeeper.property.clientPort", "2181");   
            try {
            	File workaround = new File(".");
                System.getProperties().put("hadoop.home.dir", workaround.getAbsolutePath());
                new File("./bin").mkdirs();
                new File("./bin/winutils.exe").createNewFile();
				HBaseAdmin admin = new HBaseAdmin(conf);
				if(admin.tableExists(tableName)){
					HTable table = new HTable(conf, tableName);
					List<Put> list = new ArrayList<Put>();
					File file = new File(path.getText());
					System.out.println(encode);
				    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), encode));
				    String sLine = null;   
				    while((sLine = br.readLine()) != null){
				       /*if(sLine.trim().length() > 0)
				    	   if(sLine.charAt(0) < '0' || sLine.charAt(0) > '9'){
				    		   continue;
				    	   }
					   if("".equals(sLine.trim()))
						   continue;*/
					   String[] result = sLine.split(",");
					   if(result.length != 2){
						   JOptionPane.showMessageDialog(farm, "请选择一个txt文件 ԅ(¯﹃¯ԅ)");
						   table.close();
						   br.close();
						   return;
					   }
					   Put put = new Put(Bytes.toBytes(result[0]));//rowkey
					   put.add(family[0].getBytes(), qualifier[0].getBytes(), Bytes.toBytes(result[0]));//prop:code
					   put.add(family[0].getBytes(), qualifier[1].getBytes(), Bytes.toBytes(result[1]));//prop:name
					   list.add(put);
					   System.out.println("code:"+result[0]+",name:"+result[1]);
					  }
					  br.close();
					table.put(list);
					table.close();
				}
				admin.close();
			} catch (Exception e) {
				e.printStackTrace();
			} 
            gl.setText("导入成功！");
        	gl.stop();
		}
		
		 
	}
	
}
